package com.itxh.resolver;

import com.itxh.factory.DefaultListableBeanFactory;
import com.itxh.factory.ListableBeanFactory;
import com.itxh.handler.IntegerTypeHandler;
import com.itxh.handler.StringTypeHandler;
import com.itxh.handler.TypeHandler;
import com.itxh.model.RuntimeBeanReference;
import com.itxh.model.TypedStringValue;

import java.util.ArrayList;
import java.util.List;

public class BeanDefinitionValueResolver {
    private ListableBeanFactory beanFactory;
    private List<TypeHandler> typeHandlers = new ArrayList<>();
    // 需要考虑如何初始化typeHandlers集合
    public BeanDefinitionValueResolver(DefaultListableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
//        typeHandlers = beanFactory.getBeansByType(TypeHandler.class);
        typeHandlers.add(new StringTypeHandler());
        typeHandlers.add(new IntegerTypeHandler());
    }

    public Object parseValue(Object value) {
        if (value instanceof TypedStringValue){
            TypedStringValue typedStringValue = (TypedStringValue) value;
            String stringValue = typedStringValue.getValue();
            // 该地方的targetType类型，要在解析BeanDefinition的时候，进行处理
            Class targetType = typedStringValue.getTargetType();

            return handleType(stringValue,targetType);

        }else if(value instanceof RuntimeBeanReference){
            RuntimeBeanReference reference = (RuntimeBeanReference) value;
            String ref = reference.getRef();
            // 此处容易出现循环依赖问题
            return beanFactory.getBean(ref);
        }
        return null;
    }

    // 可以考虑ListableBeanFactory接口的getBeansByType方法
    private Object handleType(String stringValue, Class targetType) {
        for (TypeHandler handler : typeHandlers) {
            if (handler.isTargetHandler(targetType)){
                return handler.handle(stringValue);
            }
        }
        return  null;
    }
}
